<template lang="pug">
  #app
    div
      keep-alive(include="Home,Discount,CategoryResults,GoodResults,Category")
        router-view(v-if="is_app_show")
      .bottom-space
      tabs(v-if="is_app_show")
      div(v-html="site_info.stats_code",v-if="is_app_show")
</template>

<script>
import Tabs from './components/Tabs'
import WxHelper from './helpers/wx_helper'
import Window from './helpers/window'
import UserInfo from './helpers/user_info'
import SiteInfo from './helpers/site_info'
import Settings from '../settings'

export default {
  name: 'App',
  components: {
    Tabs
  },
  methods: {
    getSiteInfo () {
      if (this.site_info.title) {
        this.registWechat()
        return
      }
      this.$http.get('/proxy/api/site_config').then((res) => {
        SiteInfo.set(res.body)
        this.registWechat()
      }, (err) => {
        console.log(err)
      })
    },
    registWechat () {
      if (!Window.isWechat()) {
        return
      }
      WxHelper.share(this.$wechat, this.site_info.appid, this.site_info.jsapi_ticket, window.location.href, {
        title: this.site_info.title,
        desc: this.site_info.desc,
        link: window.location.url,
        imgUrl: this.site_info.logo
      })
    },
    checkRoutePermission (route) {
      const permissions = ['callback', 'Profile', 'WithdrawRecords', 'Withdraw', 'RedPacketDetail']
      // 非微信客户端不能进入这些页面
      if (!Window.isWechat() && permissions.indexOf(route.name) !== -1) {
        this.$router.push({name: 'Home'})
      }
    },
    checkWxAuth () {
      if (Window.isWechat() && this.$route.name !== 'callback' && !this.user_info.access_token) {
        window.location = Settings.oauth2Url + this.$route.fullPath
        return
      }
      this.getSiteInfo()
    }
  },
  created () {
    if (this.$route.name === 'AppUrl') {
      return
    }

    this.checkWxAuth()
    this.checkRoutePermission(this.$route)
  },
  watch: {
    '$route': function (to, from) {
      this.registWechat()
      this.checkRoutePermission(to)
    }
  },
  computed: {
    user_info () {
      return UserInfo.get()
    },
    site_info () {
      return SiteInfo.get()
    },
    is_app_show () {
      if (Window.isWechat() && this.$route.name !== 'callback' && !this.user_info.access_token) {
        return false
      }
      return true
    }
  }
}
</script>

<style lang="sass">
@import './styles/reset.sass';
#app
  .bottom-space
    height: 42px
</style>
